package net.hvacapp.cmvrfforandroid.ui.project;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.mirror.android.common.util.StringUtils;

import net.hvacapp.cmvrfforandroid.R;
import net.hvacapp.cmvrfforandroid.adapter.BaseAdapterHelper;
import net.hvacapp.cmvrfforandroid.adapter.QuickAdapter;
import net.hvacapp.cmvrfforandroid.constant.Constant;
import net.hvacapp.cmvrfforandroid.http.BasicHttpClient;
import net.hvacapp.cmvrfforandroid.http.HttpCallbackHandle;
import net.hvacapp.cmvrfforandroid.http.HttpConstant;
import net.hvacapp.cmvrfforandroid.manager.AccountManager;
import net.hvacapp.cmvrfforandroid.manager.ProjectManager;
import net.hvacapp.cmvrfforandroid.ui.BaseActivity;
import net.hvacapp.cmvrfforandroid.ui.MainTabBarActivity;
import net.hvacapp.cmvrfforandroid.ui.project.model.GetProductDataResp;
import net.hvacapp.cmvrfforandroid.ui.project.model.GetRoomTypeGroupDataResp;
import net.hvacapp.cmvrfforandroid.ui.project.model.GuidData;
import net.hvacapp.cmvrfforandroid.ui.project.model.IndoorEquipData;
import net.hvacapp.cmvrfforandroid.ui.project.model.ProjectInfoData;
import net.hvacapp.cmvrfforandroid.ui.project.model.RoomData;
import net.hvacapp.cmvrfforandroid.ui.project.model.RoomTypeGroupData;
import net.hvacapp.cmvrfforandroid.ui.selections.model.AreaData;
import net.hvacapp.cmvrfforandroid.utils.AnnotationUtil;
import net.hvacapp.cmvrfforandroid.widget.CellSeperateLineView;
import net.hvacapp.cmvrfforandroid.widget.GroupSelectionView;
import net.hvacapp.cmvrfforandroid.widget.IOSAlertView;
import net.hvacapp.cmvrfforandroid.widget.ItemSelectionView;
import net.hvacapp.cmvrfforandroid.widget.ProjectActionView;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@EActivity(R.layout.activity_select_device_xs)
public class SelectDeviceXsActivity extends BaseActivity {

    @ViewById(R.id.lv_templete)
    ListView mTempleteLv;

    private QuickAdapter<GuidData> mQuickAdapter;

    private boolean mIsMultipleSelection;
    private ArrayList<GuidData> mSelectedData;
    private String mTag;




    /**
     * 页面加载完后执行
     */
    @AfterViews
    @Override
    protected void viewDidLoad() {
        super.viewDidLoad();
        initViews();
        initEvent();
    }

    /***
     * 初始化视图
     */
    private void initViews() {
//        mActionView.setActionInfo(ProjectManager.getInstance().getTotal(), ProjectManager.getInstance().getCurrent());
    }

    /**
     * 初始化
     */
    @Override
    public void initBoot() {
        setupToolbar(0, "选择机型", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectedData == null || mSelectedData.size() == 0) {

                    IOSAlertView.showAlertView(SelectDeviceXsActivity.this, "提示",
                            "还没有选择机型，确定返回？", "确定",
                            new IOSAlertView.OnAlertViewClickListener() {

                                @Override
                                public void OnAlertViewClick(int position) {
                                    if (position == 0) {
                                        Intent intent = new Intent();
                                        Bundle bundle = new Bundle();
                                        bundle.putParcelableArrayList("device", mSelectedData);
                                        intent.putExtras(bundle);
                                        setResult(RESULT_OK, intent);
                                        finish();
                                    }
                                }
                            }, "取消");

                }
                else {
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putParcelableArrayList("device", mSelectedData);
                    intent.putExtras(bundle);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });
        if (mQuickAdapter == null){
            mQuickAdapter = new QuickAdapter<GuidData>(context, R.layout.group_selection_cell_item) {
                @Override
                protected void convert(final BaseAdapterHelper helper, final GuidData item) {
                    final GroupSelectionView view = helper.getView(R.id.group_type);
                    view.setTitleString(item.getName());
                    view.setInfoString("");
                    view.setGroupVisible(item.isExpand());
                    if (item.isExpand()) {
                        helper.setVisible(R.id.ll_content, true);
                    }
                    else {
                        helper.setVisible(R.id.ll_content, false);
                    }
                    view.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            item.setExpand(!item.isExpand());
                            view.setGroupVisible(item.isExpand());
                            if (item.isExpand()) {
                                helper.setVisible(R.id.ll_content, true);
                            }
                            else {
                                helper.setVisible(R.id.ll_content, false);
                            }
                        }
                    });

                    LinearLayout contentLl = helper.getView(R.id.ll_content);
                    contentLl.removeAllViews();
                    for (final GuidData rItem : item.getXsData()) {
                        CellSeperateLineView line = new CellSeperateLineView(SelectDeviceXsActivity.this);
                        contentLl.addView(line);

                        final ItemSelectionView itemView = new ItemSelectionView(SelectDeviceXsActivity.this);
                        itemView.setTitleString(rItem.getName());
                        itemView.setItemSelected(item.isSelected());
                        itemView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //选择了这个型式
                                if (mIsMultipleSelection) {
                                    ImageView ivSelectMark = (ImageView) itemView.findViewById(R.id.iv_selected_mark);
                                    if (rItem.isSelected()) {
                                        rItem.setSelected(false);
                                        ivSelectMark.setVisibility(View.INVISIBLE);
                                    } else {
                                        rItem.setSelected(true);
                                        ivSelectMark.setVisibility(View.VISIBLE);
                                    }
                                    resetSelectedData(rItem);
                                } else {

                                    if (mSelectedData == null) {
                                        mSelectedData = new ArrayList<GuidData>();
                                    }
                                    else {
                                        mSelectedData.clear();
                                    }
                                    mSelectedData.add(rItem);
                                    Intent intent = new Intent();
                                    Bundle bundle = new Bundle();
                                    bundle.putParcelableArrayList("device", mSelectedData);
                                    intent.putExtras(bundle);
                                    setResult(RESULT_OK, intent);
                                    finish();
                                }
                            }
                        });
                        contentLl.addView(itemView);
                    }
                }
            };
        }

        mTempleteLv.setAdapter(mQuickAdapter);
    }


    /**
     * 初始化数据
     */
    @Override
    public void initData(Intent intent) {
        mIsMultipleSelection = intent.getBooleanExtra("multiple", true);
        mSelectedData = intent.getParcelableArrayListExtra("device");
        mTag = intent.getStringExtra("tag");

        loadProjectSelectedSeries();
    }



    /**
     * 页面名称
     */
    @Override
    public String getName() {
        return "";
    }

    private void initEvent() {

    }


    /**
     *  获取项目中选择了的系列
     */
    private void loadProjectSelectedSeries() {
        Map<String, Object> param = new HashMap<>();
        param.put("pid", ProjectManager.getInstance().getProjectData().getGuidId());
        param.put("tag", mTag);

        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_PROJECT_PRODUCT_SERIES, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetProductDataResp>() {
            @Override
            public void onSuccess(GetProductDataResp obj) {
                // 成功
                if (obj.getGetCandidateXlsResult() != null && obj.getGetCandidateXlsResult().size() > 0) {
                    for (GuidData item : obj.getGetCandidateXlsResult()) {
                        loadSelectedXs(mTag, item);
                    }
                }
            }

            @Override
            public void onFailure(String response) {
                showMessage("获取系列失败，请重试！");
            }
        });
    }

    /**
     *  获取项目中选择了的型式列表(室内机和轻型商用空调)
     *
     *  @param data 系列
     *  @param tag   系列数据
     */
    private void loadSelectedXs(final String tag, final GuidData data) {
        Map<String, Object> param = new HashMap<>();
        param.put("xl", data.getGuidId());
        param.put("tag", tag);
        param.put("ac", 1); //0 仅包括未上市  1 仅包括已上市 2 已上市未上市都包括


        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_PROJECT_PRODUCT_XS_BY_XL, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetProductDataResp>() {
            @Override
            public void onSuccess(GetProductDataResp obj) {
                // 成功
                if (obj.getGetProductXssResult() != null && obj.getGetProductXssResult().size() > 0) {
                    for (GuidData item : obj.getGetProductXssResult()) {
                        loadProductsByXs(mTag, item);
                    }
                }
            }

            @Override
            public void onFailure(String response) {
                showMessage("获取型号失败，请重试！");
            }
        });
    }

    /**
     *  通过型式获得产品型号
     *
     *  @param tag  类型
     *  @param data 型式数据
     */
    private void loadProductsByXs(final String tag, final GuidData data) {
        Map<String, Object> param = new HashMap<>();
        param.put("xs", data.getGuidId());
        param.put("tag", tag);
        param.put("dfr", ProjectManager.getInstance().getProjectData().getDfrType());
        param.put("power", ProjectManager.getInstance().getProjectData().getPowerType());
        param.put("ac", 1); //0 仅包括未上市  1 仅包括已上市 2 已上市未上市都包括
        param.put("si", 0);
        param.put("ei", -1);

        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_PROJECT_PRODUCT_BY_XS, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetProductDataResp>() {
            @Override
            public void onSuccess(GetProductDataResp obj) {
                // 成功
                if (obj.getGetProductsByXsResult() != null && obj.getGetProductsByXsResult().size() > 0) {
                    List<GuidData> xs = new ArrayList<GuidData>();
                    if (mSelectedData != null && mSelectedData.size() > 0) {
                        for (int i = 0; i < obj.getGetProductsByXsResult().size(); i++) {
                            GuidData item = obj.getGetProductsByXsResult().get(i);
                            for (int j = 0; j < mSelectedData.size(); j++) {
                                if (StringUtils.isEquals(item.getGuidId(), mSelectedData.get(j).getGuidId())) {
                                    item.setSelected(true);
                                    break;
                                }
                            }
                        }
                    }
                    xs.addAll(obj.getGetProductsByXsResult());
                    data.setXsData(xs);
                    mQuickAdapter.add(data);
                }
            }

            @Override
            public void onFailure(String response) {
                showMessage("获取产品失败，请重试！");
            }
        });
    }


    private void resetSelectedData(GuidData data) {
        if (data.isSelected()) {
            if (mSelectedData == null) {
                mSelectedData = new ArrayList<>();
            }
            boolean hasSame = false;
            for (GuidData item : mSelectedData) {
                if (StringUtils.isEquals(data.getGuidId(), item.getGuidId())) {
                    hasSame = true;
                    break;
                }
            }
            if (!hasSame) {
                mSelectedData.add(data);
            }
        }
        else {
            if (mSelectedData != null && mSelectedData.size() > 0) {
                for (GuidData item : mSelectedData) {
                    if (StringUtils.isEquals(data.getGuidId(), item.getGuidId())) {
                        mSelectedData.remove(item);
                        break;
                    }
                }
            }
        }
    }

}
